<html>
    <head>
        <title>Sale History</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="logo">
            <h1><a href="#">Sale History</a></h1>
        </div>
        <form>
            <br/>
            <br/>
            <div id='infotab' name='infotab'>
                <div class='field'>
                   From:<input type='text' style='width:65px' id='fromdate' name='fromdate' value='' /><img src='datechooser.png' onclick='ShowDatePad(document.all.fromdate,0);'>to: <input type='text' style='width:65px' id='todate' name='todate' value='' /><img src='datechooser.png' onclick='ShowDatePad(document.all.todate,0);'>
                </div>
                <div class='field'>
                   <input type='button' id='infobutton' onclick='FixDate(0);' value='Go'> <input type='button' id='infobutton' onclick='FixDate(1);' value='Today'><input type='button' id='itemsbutton' onclick='FixDate(2);' value='Month' /><input type='button' id='searchbutton' onclick='FixDate(3);' value='Year' />
                </div>
                <div class='field'>
                    <input type='button' id='infobutton' onclick='javascript:location.replace("index.html");' value='Exit'>
                </div><span id='results' name='results'></span>
				
            </div>
			<div id='datepad' name='datepad' style='display:none;'></div>
        </form>
        <!-- ====================================== -->
        <!-- End HTML code.  Begin JavaScript code. -->
        <script type="text/javascript" src="gears_init.js">
        </script>
        <script type="text/javascript" src="scripts.js">
        </script>
        <script>
            
            //todo: sum paytypes from sales and payments
            //
            
            var db;
            var dbSaleName = '';
            var dbSaleItemName = '';
            var dbSalePaymentName = '';
            var CustomerPaymentDBName = '';
			var currentYear = '';
            var historyBookmark = 0;
            
            init();
            
			
			
			 function ChangeTab(item){
			 
			 	if (item == 8) //datepad
						document.all.datepad.style.display = 'inline';
					else 
						document.all.datepad.style.display = 'none';
				if (item == 0) //info
						document.all.infotab.style.display = 'inline';
					else 
						document.all.infotab.style.display = 'none';
				}
			
            function FixDate(option){
            
                var from = document.all.fromdate;
                var to = document.all.todate;
                var currentDate = new Date();
                
                if (option == 1) //day 
                {
                    var fromdate = currentDate.getDate();
                    
					from.value = currentDate.getMonth() + 1 + '/' + fromdate + '/' + currentDate.getFullYear();
                    to.value = currentDate.getMonth() + 1 + '/' + fromdate + '/' + currentDate.getFullYear();
                }
                if (option == 2) //month 
                {
                    var month = currentDate.getMonth();
                    month++;
                    
                    lastday = '/30/';
					if(month==0 | month==2 | month==4 | month==6| month==7| month==9| month==11)
						lastday = '/31/';
					if(month==1)
					{	if(currentDate.getFullYear() % 4 == 0)
							lastday = '/29/';
						else
							lastday = '/28/';
					}
					
                    from.value = month + '/01/' + currentDate.getFullYear();
                    to.value = month + lastday + currentDate.getFullYear();
                }
                if (option == 3) //year
                {
                    from.value = '01/01/' + currentDate.getFullYear();
                    to.value = '12/31/' + currentDate.getFullYear();
                }
				
				//alert(tod);
                //if (fromd.getFullYear() != tod.getFullYear()) {
                //    alert('Dates must be within same year');
               //     return;
              //  }
                 var fromd = new Date(from.value);
                dbSaleName = 'Sale_' + fromd.getFullYear();
                dbSaleItemName = 'SaleItem_' + fromd.getFullYear();
                dbSalePaymentName = 'SalePayment_' + fromd.getFullYear();
                CustomerPaymentDBName = 'CustomerPayment_' + fromd.getFullYear();
                historyBookmark = 0;
                getHistory(from.value, to.value, 0);
            }
            
            
            function getHistory(from, to, option){
            
				//alert(from.value);
                var from1 = new Date(from);
                var to1 = new Date(to);
                
				
				currentYear = from1.getFullYear();
				from1.setDate(from1.getDate() - 1);
				to1.setDate(to1.getDate() + 1);
				var fromd = FormatDate((from1.getMonth()+1)+ '/'+ from1.getDate() +'/' +from1.getFullYear());
                var tod = FormatDate((to1.getMonth()+1)+ '/'+ to1.getDate() +'/' +to1.getFullYear());
                
                var history = document.all.results;
                var html = "";// "<table border='1'>";
                //html += "<th class='itemth' width='50' >Date</th><th class='itemth' width='50'>Type</th><th class='itemth'  width='50' >Info</th><th class='itemth'  width='50' >Total</th>";
                
                //get sales
                
                var query = "select saledate as tdate, 0 as ttype, saleid,'paytypeplaceholder' as paytype, sum((qty*price)+taxes) as total,firstname,middlename,lastname from " + dbSaleName;
                query += " s inner join " + dbSaleItemName + " on s.id=saleid"
                query += " inner join customer c on customerid=c.id";
                query += " group by saledate,saleid ";
                if (from != null) 
                    query += "having saledate>'" + fromd + "' and saledate< '" + tod + "'";
                //query+=" order by 1,3 desc";
                
                //get payments 
                query += " union select date(paymentdate) as tdate, 1 as ttype,cp.id, paytype, amount as total,firstname,middlename,lastname";
                query += " from " + CustomerPaymentDBName;
                query += " cp inner join customer c on customerid=c.id";
                if (from != null) 
                    query += " where paymentdate >'" + fromd + "' and paymentdate < '" + tod + "'";
                query += " order by 1 desc,3 desc";
                
                //row count control
                historyBookmark = historyBookmark + option;
                if (historyBookmark < 0) 
                    historyBookmark = 0;
                
                query += " limit 10 offset " + historyBookmark;
                
                var rs = db.execute(query);
                var count = 0;
                while (rs.isValidRow()) {
                    if (count >= 20) 
                        break;
                    var type = '';
                    var info = '';
                    if (rs.field(1) == 1) {
                        type = 'Payment  <a href="#" onclick="DeletePayment('+ rs.field(2) +')">(delete)</a>'
                        info = rs.field(3);
                    }
                    else {
                        type = 'Sale <a href="#" onclick="DeleteSale('+ rs.field(2) +')">(delete)</a>';
                      //  info = "<a href='saleview.html?id=" + rs.field(2) + "'>[View]</a>";
						info = "<a href='saleview.html?id=" + rs.field(2) + "&year="+ currentYear +"'>[View]</a>";
                    }
                    var name = getFullName(rs.field(5), rs.field(6), rs.field(7))
                    var date = new Date(rs.field(0));
                    var days = ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'];
                    //+ ": " + days[date.getDay()]
                    html += SearchResult2(formatNumber(rs.field(4), true), name, type, rs.field(0), info);
                    
                    /*if (count % 2 == 0) 
                     html += "<tr><td class='itemtd' style='width:50px'>" + rs.field(0) + "</td><td class='itemtd' >" + type + "</td><td class='itemtd' >"+info+"</td><td class='itemtd' >" + formatNumber(rs.field(3),true)  + "</td></tr>";
                     else
                     html += "<tr><td class='itemtdpar' style='width:50px'>" + rs.field(0) + "</td><td class='itemtdpar' >" + type + "</td><td class='itemtdpar' >"+info+"</td><td class='itemtdpar' >" + formatNumber(rs.field(3),true)  + "</td></tr>";
                     */
                    count++;
                    rs.next();
                }
                
                if (historyBookmark >= 10) 
                    html += "<a href=# onclick='getHistory(\"" + from + "\",\"" + to + "\",-10)'>[Back 10]</a>";
                if (count >= 10) 
                    html += "<a href=# onclick='getHistory(\"" + from + "\",\"" + to + "\",10)'>[Next 10]</a>";
                //html += "</table>";
                history.innerHTML = html;
                
                rs.close();
                
            }
            
            
            
            
            // Open this page's local database.
            function init(){
                var success = false;
                
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('psdb');
                            
                            
                            var currentDate = new Date();
                            dbSaleName = "Sale_" + currentDate.getFullYear();
                            dbSaleItemName = "SaleItem_" + currentDate.getFullYear();
                            dbSalePaymentName = "SalePayment_" + currentDate.getFullYear();
                            CustomerPaymentDBName = 'CustomerPayment_' + currentDate.getFullYear();
                            success = true;
                            // Initialize the UI at startup.
                        
                            //displayRecentPhrases();
                            // loadSaleTypes('');
                        }
                        
                    } 
                    catch (ex) {
                        setError('Could not create database: ' + ex.message);
                        alert('Could not create database: ' + ex.message);
                    }
                }
                
                // Enable or disable UI elements
                
                var inputs = document.forms[0].elements;
                for (var i = 0, el; el = inputs[i]; i++) {
                    el.disabled = !success;
                }
                
            }
			
			  function DeleteSale(id){
                if (id > 0) {
                
                    var a = confirm('Delete the sale?');
                    if (a != false) {
                    
					 
						db.execute('delete from '+dbSaleItemName+' where saleid=?', [id]);
						db.execute('delete from '+dbSalePaymentName+' where saleid=?', [id]);
                        
                        db.execute('delete from '+ dbSaleName +' where id=?', [id]);
                        alert('Sale deleted!');//
                        location.replace('salehistory.html');
                        //Load first record as default..or display a top 20 search? 
                       // var rs = db.execute('select top 1 id from Product');
                        //rs.close();
                      //  Search('', 0);
                    }
                }
                
            }
			 function DeletePayment(id){
                if (id > 0) {
                
                    var a = confirm('Delete the payment?');
                    if (a != false) {
                    
                        db.execute('delete from '+ CustomerPaymentDBName+ ' where id=?', [id]);
                        alert('Payment deleted!');//
                        //Load first record as default..or display a top 20 search? 
                        location.replace('salehistory.html');
                    }
                }
                
            }
            
            /*  sql payments
            
             * select sum(total), paytype from(
            
             select sum(amount)as total , paytype from salepayment_2009  inner join sale_2009 s on s.id=saleid
            
             group by paytype
            
             having saledate> '1/01/2009' and  saledate< '12/01/2009'
            
             union
            
             select sum(c.amount),paytype from  customerpayment_2009 c
            
             group by paytype
            
             having paymentdate> '1/01/2009' and  paymentdate< '12/01/2009'
            
             ) as totals
            
             group by paytype
            
             *
            
             */
            
        </script>
        <!-- <xml id="xmlTitles" src="./Sales.xml?root='Sales'">
        </xml>-->
    </body>
</html>
